package com.itheima.controller;

import com.css.tliasspringbootstarterautoconfigure.utils.AliOSSUtils;
import com.itheima.pojo.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.UUID;

@RestController
public class FileUpload {
    @Autowired
    private AliOSSUtils aliOSSUtils;
    /**
     * 文件上传到本地
     * @param image
     */
    @PostMapping("/upload1")
    public void upload(MultipartFile image){
        //获取文件扩展名
        String originalFilename = image.getOriginalFilename();
        int index = originalFilename.lastIndexOf(".");
        String substring = originalFilename.substring(index);
        //获取随即名
        String s = UUID.randomUUID().toString();
        //拼接成新文件名
        String newFileName=s+substring;
        //将接收到的文件转存到磁盘文件中
        try {
            image.transferTo(new File("C:\\Users\\36204\\Desktop\\Java190\\tlias\\src\\main\\java\\com\\itheima",newFileName));
        } catch (IOException e) {
            Result.error("文件上传失败");
        }
    }
    /**
     * 文件上传到阿里云OSS
     */
    @PostMapping("/upload")
    public Result uploadOSS(MultipartFile image){
        //上传到阿里云
        try {
            String url = aliOSSUtils.upload(image);
            //返回URL给前端
            return Result.success(url);
        } catch (IOException e) {
            return Result.error("文件上传失败");
        }
    }
}

